const Koa = require('koa');
const app = new Koa();

// const fs = require('fs.promised');
// const compose = require('koa-compose');
// const route = require('koa-route');
const router = require('koa-router')();
// const serve = require('koa-static');
const koaBody = require('koa-body');
const os = require('os');
const path = require('path');
// const getRawBody = require('raw-body');
// var contentType = require('content-type');

// const main = (ctx, next) => {
//   console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
//   next();
// };
// app.use(main);


// app.use(koaBody({ multipart: true }));


router.get('/form',
  (ctx) => {
    // 虽然 name 值没有[]，但多个文件时，结果中仍然是多个文件。非常正确的操作。
    ctx.body = `
    <form action="/file" method="POST" enctype="multipart/form-data">
      <input type="file" name='image' multiple /><br/>
      <input type="submit" name="smt" value="上传文件" />
    </form>`;
  }
);

// router.post('/file', koaBody({ multipart: true }),
router.post('/file', koaBody({ multipart: true }),
  (ctx) => {
    console.log(ctx.request.body.files.image);
    // => POST body
    // ctx.body = JSON.stringify(ctx.request.body);
    ctx.body = 'hello file';
  }
);
 
app.use(router.routes());



app.listen(8080);
console.log('server listening at 8080');
